package org.cem.backend;

import javax.security.auth.login.LoginException;

import org.cem.security.CemSecurityPlugin;
import org.eclipse.rap.rwt.application.EntryPoint;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;

public class BackendEntryPoint implements EntryPoint {

	private Display display;
	private Shell shell;

	/**
	 * This method is called by the framework to initialize the UI. Subclasses should implement
	 * {@link #createContents(Composite)} instead of overriding this method.
	 *
	 * @nooverride This method is not intended to be re-implemented or extended by clients.
	 */
	public int createUI() {
	  display = PlatformUI.createDisplay();
//	  shell = createShell( display );
	  
//	  Realm.runWithDefault(SWTObservables.getRealm(display), new Runnable() {
//		  public void run() {
//			  shell.setLayout( new GridLayout( 1, false ) );
//			  createContents( shell );
//			  if( shell.getMaximized() ) {
//				  shell.layout();
//			  } else {
//				  shell.pack();
//			  }
//			  shell.open();
//
//			  while (!shell.isDisposed()) {
//				  if (!display.readAndDispatch()) {
//					  display.sleep();
//				  }
//			  }
//		  }
//	  });
//	  display.dispose();
	  
//	  if( getApplicationContext().getLifeCycleFactory().getLifeCycle() instanceof RWTLifeCycle ) {
//		  while( !shell.isDisposed() ) {
//			  if( !display.readAndDispatch() ) {
//				  display.sleep();
//			  }
//		  }
//		  display.dispose();
//	  }

		try {
			 CemSecurityPlugin.getLoginContext().login();
		} catch (LoginException e) {
		  Throwable cause = e.getCause();
		  if( cause != null && cause.getCause() instanceof ThreadDeath ) {
		    throw ( ThreadDeath )cause.getCause();
		  }
		}
	    int result = 0;
	    try {
	      result = PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor());
	    } catch( Exception e ) {
	      e.printStackTrace();
	    } finally {
//	    	display.dispose();
//	      	try {
//	      		CemSecurityPlugin.getLoginContext().logout();
//			} catch (LoginException e) {
//				e.printStackTrace();
//			}
	    }
	    return result;
	  }

	/**
	 * Returns the main shell for this entrypoint.
	 *
	 * @return the main shell, or <code>null</code> if the shell is not created yet
	 */
	protected Shell getShell() {
	  return shell;
	}

	/**
	 * Creates the main shell for this entrypoint. The default implementation creates a maximized
	 * shell without any trimmings. Subclasses may override this method in order to create a different
	 * kind of shell.
	 *
	 * @param display the display to create the shell on
	 * @return the created shell
	 */
	protected Shell createShell(Display display) {
	  Shell shell = new Shell(display, SWT.NO_TRIM);
	  shell.setMaximized(false);
	  return shell;
	}

}
